#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <qmosquitto.h>
#include <QtDebug>
#include <QMessageBox>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    socket = new QMosquitto(this);
//    socket->setHostname("127.0.0.1");
////    socket->setUsername("cz");
////    socket->setPassword("111111");
//    socket->setPort(8884);
////    socket->setClientId("08-ssl-connect-crt-auth");

//    //mosquitto_sub -t test-topic -h 127.0.0.1 -p 8884 --cafile /home/cps/mqtt/cert/ca.crt --cert /home/cps/mqtt/cert/client.crt --key /home/cps/mqtt/cert/client.key
//    socket->setTlsEnabled(true);
//    socket->setTls_ca("/home/cps/mqtt/cert/ca.crt");
//    socket->setTls_capath("/home/cps/mqtt/cert");
//    socket->setTls_cert("/home/cps/mqtt/cert/client.crt");
//    socket->setTls_key("/home/cps/mqtt/cert/client.key");

//    qDebug() << __LINE__ << socket->connectToHost();

    connect(socket, SIGNAL(msg(QString,QString)), this, SLOT(slotGetMsg(QString, QString)));
    connect(socket, SIGNAL(connected()), this, SLOT(slotConnected()));
    connect(socket, SIGNAL(error()), this, SLOT(slotError()));

}

MainWindow::~MainWindow()
{
    delete ui;
}


/*
mosquitto_pub -h localhost -t test-topic -m "Hello, MQTT!"
mosquitto_sub -h localhost -t test-topic

*/
void MainWindow::on_pushButton_clicked()
{
    QString message = "Hello, MQTT!";
    socket->publish("test-topic", message);
    ui->textEdit_publish->append("SEND:test-topic/" + message);
}

void MainWindow::on_pushButton_2_clicked()
{
    socket->subscribe("test-topic");
}

void MainWindow::slotGetMsg(QString topic, QString data)
{
    ui->textEdit_subscribe->append("RECEIVE:" + topic + "/" + data);
}

void MainWindow::on_pushButton_login_clicked()
{
    const int type = ui->comboBox->currentIndex();

    if(socket->isConnected())
        socket->disconnectFromHost();
    socket->setHostname(ui->lineEdit_host->text());
    socket->setPort(ui->comboBox_port->currentText().toInt());
    socket->setUsername(ui->lineEdit_user->text());
    socket->setPassword(ui->lineEdit_pwd->text());
    socket->setTlsEnabled(type == 2);
    socket->setTls_cafile(ui->lineEdit_ca->text());
    socket->setTls_capath(ui->lineEdit_capath->text());
    socket->setTls_cert(ui->lineEdit_cert->text());
    socket->setTls_key(ui->lineEdit_key->text());

    socket->connectToHost();
}

void MainWindow::slotConnected()
{
    QMessageBox::information(this, " ", QString::fromUtf8("登陆成功"));

    socket->subscribe("test-topic");
    ui->textEdit_publish->clear();
    ui->textEdit_subscribe->clear();
}

void MainWindow::slotError()
{
    QMessageBox::warning(this, " ", socket->lastErrorString());
}
